package com.yishan.controller;

import com.github.pagehelper.PageInfo;
import com.yishan.domain.Module;
import com.yishan.service.ModuleService;
import com.yishan.utils.BeanUtil;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Author yishan
 * @Date 2021/4/28 0028 1:20
 * @Version 1.0
 */
@Controller
@RequestMapping("/module")
public class ModuleController {

	@Autowired
	private ModuleService moduleService;


	/**
	 * 查询所有
	 *
	 * @param model
	 * @param request
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping("/list")
	private String list(Model model, HttpServletRequest request)
			throws ServletException, IOException {

		int page = 1;
		int size = 10;

		if (StringUtils.isNotBlank(request.getParameter("page"))) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (StringUtils.isNotBlank(request.getParameter("size"))) {
			size = Integer.parseInt(request.getParameter("size"));
		}

		PageInfo info = moduleService.findAll(page, size);

		model.addAttribute("page", info);

		return "/WEB-INF/pages/module/list.jsp";

	}

	/**
	 * 跳转到添加页面
	 *
	 * @return
	 */
	@RequestMapping("/toAdd")
	private String toAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		List<Module> moduleList = moduleService.findAll();
		request.setAttribute("moduleList",moduleList);

		request.getRequestDispatcher("/WEB-INF/pages/module/add.jsp")
				.forward(request, response);

		return "/WEB-INF/pages/module/add.jsp";

	}

	/**
	 * 添加操作
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/save")
	private String save(HttpServletRequest request) {

		Module module = BeanUtil.fillBean(request, Module.class);
		moduleService.save(module);

		return "redirect:" + request.getContextPath() + "/module/list";

	}

	/**
	 * 跳转到修改页面
	 *
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/toEdit")
	private String toEdit(String id, Model model) {

		Module module = moduleService.findById(id);
		model.addAttribute("module", module);

		List<Module> moduleList = moduleService.findAll();
		model.addAttribute("moduleList", moduleList);
		return "/WEB-INF/pages/module/update.jsp";

	}

	/**
	 * 修改操作
	 *
	 * @param module
	 * @return
	 */
	@RequestMapping("/edit")
	private String edit(Module module) {

		moduleService.update(module);

		return "redirect:/module/list";

	}

	/**
	 * 删除操作
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete")
	private String delete(String ids) {

		moduleService.deleteMany(ids);

		return "redirect:/module/list";

	}

}
